const sqlExecute = require('../../database/wechat/query')
const dayjs = require('dayjs')

// 获取菜单
const getMenu = async (req, res) => {
  const sql = `SELECT * FROM menu where is_deleted = 0 and parentId = 0`
  const result = await sqlExecute(sql)

  for ( const item of result ) {
    if ( item.parentId === 0 ) {
      const sql = 'SELECT * FROM menu where parentId = ? and is_deleted = 0'
      item.children = await sqlExecute(sql, [item.id])
    }
  }

  res.send({
    status: 1,
    code: 20000,
    data: result,
  })
}

// 获取单个菜单
const getOneMenu = async (req, res) => {
  const id = req.params.id
  const sql = 'SELECT * FROM menu where id = ?'
  const result = await sqlExecute(sql, [id])

  res.send({
    status: 1,
    code: 20000,
    data: result[0],
  })
}

// 更新菜单
const updateMenu = async (req, res) => {
  const menuInfo = req.body
  const id = req.body.id
  // 删除创建时间字段
  delete menuInfo.createTime
  menuInfo.updateTime = dayjs(menuInfo.updateTime).format('YYYY-MM-DD HH:mm:ss')

  const sql = 'UPDATE menu SET ? WHERE id = ?'
  const result = await sqlExecute(sql, [menuInfo, id])

  res.send({
    status: 1,
    code: 20000,
    message: '更新成功',
    data: result,
  })
}

// 新增菜单
const saveMenu = async (req, res) => {
  const menuInfo = req.body
  menuInfo.createTime = dayjs(menuInfo.createTime).format('YYYY-MM-DD HH:mm:ss')
  menuInfo.updateTime = dayjs(menuInfo.updateTime).format('YYYY-MM-DD HH:mm:ss')

  // 过滤空字段
  const menuInfoFilter = {}
  for ( const key in menuInfo ) {
    if ( menuInfo[key] !== '' && menuInfo[key] !== null ) {
      menuInfoFilter[key] = menuInfo[key]
    }
  }


  const sql = 'INSERT INTO menu SET ?'
  const result = await sqlExecute(sql, menuInfoFilter)

  res.send({
    status: 1,
    code: 20000,
    message: '新增成功',
    data: result,
  })
}

// 删除菜单
const deleteMenu = async (req, res) => {
  const id = req.params.id
  const sql = 'UPDATE menu SET is_deleted = 1 WHERE id = ?'
  const result = await sqlExecute(sql, [id])

  res.send({
    status: 1,
    code: 20000,
    message: '删除成功',
    data: result,
  })
}

module.exports = {
  getMenu,
  getOneMenu,
  updateMenu,
  saveMenu,
  deleteMenu,

}
